package com.cf.base.sp.engine.impl;

import com.cf.base.sp.bean.SerializerInfo;
import com.cf.base.sp.bean.ObjectType;
import com.cf.base.sp.engine.Serializer;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 序列化
 *
 * @author yangji
 */
public class DefaultSerializerImpl implements Serializer {


    @Override
    public <T> String serialize(T t, String content) {

        SerializerInfo info = new SerializerInfo();

        if (t instanceof List) {
            info.type = ObjectType.List;
            List list = (List) t;
            if (!list.isEmpty()) {
                info.valueClass = list.get(0).getClass().getName();
            }
        } else if (t instanceof Set) {
            info.type = ObjectType.Set;
            Set set = (Set) t;
            if (!set.isEmpty()) {
                Iterator iterator = set.iterator();
                if (iterator.hasNext()) {
                    info.valueClass = iterator.next().getClass().getName();
                }
            }
        } else if (t instanceof Map) {
            info.type = ObjectType.Map;
            Map map = (Map) t;
            if (!map.isEmpty()) {
                for (Object key : map.keySet()) {
                    Object value = map.get(key);
                    if (value != null) {
                        info.keyClass = key.getClass().getName();
                        info.valueClass = value.getClass().getName();
                        break;
                    }
                }
            }
        } else {
            info.type = ObjectType.Object;
            info.valueClass = t.getClass().getName();
        }

        return info.type.name() + "#" + info.keyClass + "#" + info.valueClass + "#" + content;
    }

    @Override
    public SerializerInfo deserialize(String fileContent) {
        SerializerInfo info = new SerializerInfo();
        String[] infos = fileContent.split("#");
        ObjectType type = ObjectType.valueOf(infos[0]);
        String keyClass = infos[1];
        String valueClass = infos[2];
        info.content = infos[3];
        info.type = type;
        info.keyClass = keyClass;
        info.valueClass = valueClass;
        return info;
    }
}
